package com.agriculture.controller;

import com.agriculture.common.OrderStatus;
import com.agriculture.entity.Good;
import com.agriculture.entity.Orders;
import com.agriculture.mapper.GoodMapper;
import com.agriculture.mapper.OrderGoodMapper;
import com.agriculture.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/api")
@Slf4j
public class ApiController {

    @Resource
    private GoodMapper goodsMapper;

    @Resource
    private OrderMapper ordersMapper;

    @Resource
    private OrderGoodMapper orderGoodMapper;

    @GetMapping("/goods")
    public List<Good> getGoods() {
        return goodsMapper.selectList(null);
    }

    @GetMapping("/orders")
    public List<Orders> getOrders() {
        return ordersMapper.selectList(null);
    }

    @Transactional
    @PostMapping("/buy")
    public boolean buy1(@RequestParam Long goodsId, @RequestParam Long userId) {
        Good goods = goodsMapper.selectById(goodsId);
        int store = goods.getStore() - 1;
        if (store < 0) {
            return false;
        }
        Date date = new Date();
        Orders orders = new Orders();
        orders.setStatus(OrderStatus.ORDERED);
        orders.setUserId(userId);
        orders.setOrderNumber(new SimpleDateFormat("yyyyMMdd").format(date) + System.currentTimeMillis());
        BigDecimal price = goods.getPrice();
        BigDecimal amount = orders.getAmount().add(price.multiply(BigDecimal.ONE));
        orders.setAmount(amount);

        goods.setStore(store);
        int insert = ordersMapper.insert(orders);
        int update = goodsMapper.updateById(goods);
        if(insert <= 0 || update <= 0){
            return false;
        }else{
            return true;
        }

    }

}

















